var express = require("express");
var expressWs = require("express-ws");
var router = express.Router();

expressWs(router);

let clients = {};
let clientNum = 0;

router
  .ws("/", function (ws, req) {
    let name = req.query.name.trim();
    console.log("connect success, ip: " + req.ip);
    console.log("connect success, name: " + name);
    let flag = true;

    for (const key in clients) {
      if (Object.hasOwnProperty.call(clients, key)) {
        const ele = clients[key];
        if (name == ele.name) {
          console.log("有相同名称");
          flag = false;
          break;
        }
      }
    }

    if (!flag) {
      console.log("拦截");
      ws.send(
        JSON.stringify({
          content: "昵称已存在",
          flag: false,
          type: "err",
        })
      );
      return;
    }

    //给客户端编号,也就是参与聊天的用户
    ws.id = ++clientNum;
    ws.name = name;
    clients[ws.id] = ws;
    // console.log(clients);

    // 使用 ws 的 send 方法向连接另一端的客户端发送数据
    broadcast(ws, {
      name: ws.name,
      content: "我上线了!",
      flag: true,
      type: "login",
      id: ws.id,
    });

    // 使用 on 方法监听事件
    //   message 事件表示从另一段（服务端）传入的数据
    ws.on("message", function (json) {
      json = JSON.parse(json) || false;
      json = json.json;
      if (!json) {
        broadcast(ws, false);
        return;
      }
      console.log(json);
      // ws.send("default response");
      console.log("用户" + ws.name + "说:" + json.content);
      // console.log(JSON.parse(json));
      //广播数据发送输出
      broadcast(ws, {
        name: ws.name,
        content: json.content,
        flag: true,
        type: "msg",
        id: ws.id,
      });
    });

    // 设置定时发送消息
    // let timer = setInterval(() => {
    //   ws.send(`interval message ${new Date()}`);
    // }, 2000);

    // close 事件表示客户端断开连接时执行的回调函数
    ws.on("close", function (e) {
      console.log("用户" + ws.name + "离线了");
      for (const key in clients) {
        if (Object.hasOwnProperty.call(clients, key)) {
          const element = clients[key];
          if (element == ws) {
            console.log("找到了，准备T掉");
            delete clients[ws.id];
          } else {
            console.log("没找到....");
          }
        }
      }
      broadcast(ws, {
        name: ws.name,
        content: "我离线了",
        flag: true,
        type: "logout",
        id: ws.id,
      });
    });
  })
  .post("/clients", function (req, res, next) {
    res.json({ json: clients });
  });

//广播方法
function broadcast(client, json) {
  for (var key in clients) {
    clients[key].send(JSON.stringify(json));
  }
}

module.exports = router;
